package com.bite.java_chatroom.controller;

import com.bite.java_chatroom.component.OnlineUserManager;
import com.bite.java_chatroom.model.UserInfo;
import com.bite.java_chatroom.service.UserInfoService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private OnlineUserManager userManager;
    @Autowired
    UserInfoService userInfoService;

    @RequestMapping("/login")
    @ResponseBody
    public UserInfo login(String username, String password, HttpSession session){
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            return new UserInfo();
        }
        UserInfo userInfo = userInfoService.login(username);
        if(userInfo == null || !userInfo.getPassword().equals(password)){
            log.info("登录失败username："+username);
            return new UserInfo();
        }
        Integer userId = userInfoService.selectIdByUserName(username);
        if(!userManager.online(userId,null)){
            log.info("登录失败: 用户["+username+"]已上线");
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setId(-1);
            return userInfo1;
        }
        userInfo.setPassword("");
        session.setAttribute("session_user_info",userInfo);
        return userInfo;
    }

    @RequestMapping("/register")
    public Integer register(String username, String password){
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            //返回0 用户名或密码为空
            return 0;
        }
        UserInfo userInfo = userInfoService.login(username);
        if(userInfo != null && userInfo.getUsername().equals(username)){
            //返回2 用户名已存在
            return 2;
        }
        try {
            //返回1 注册成功
            userInfoService.register(username,password);
            return 1;
        }catch (Exception e){
            log.warn("用户注册失败username："+username);
            //返回0 注册失败
            return 0;
        }
    }

    @RequestMapping("/getName")
    public UserInfo getUserName(HttpSession session){
        if(session==null){
            log.info("[getUserName erro] 获取session失败");
            return new UserInfo();
        }
        UserInfo userInfo = (UserInfo) session.getAttribute("session_user_info");
        if(userInfo==null){
            log.info("[getUserName erro] 获取userinfo失败");
            return new UserInfo();
        }
        userInfo.setPassword("");
        return userInfo;
    }
}





